import React, { Component } from 'react';
import ExportJsonExcel from 'js-export-excel';
import { Col, Table, Space, Row, message, Button, Upload } from 'antd';
import {
  DeleteOutlined,
  PlusOutlined,
  InboxOutlined,
  DeleteFilled,
} from '@ant-design/icons';
import 'antd/dist/antd.css';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {
  getDictionaryLabel,
  getAjaxurl,
  devProTest,
} from '../../../rudexRou/OperatesCookie.js';
import { confirmDeptByCode, getUrl } from '../../../utils';
import {
  getCandidate,
  getEmpInExam,
  delEmpInExam,
  addEmpToExam,
} from '../../../api3';
import { exportRisk } from '../../../api';
import AdvancedSearchForm from '../../../componentJsx/common/searchForm';
import HasPermi from '../../../componentJsx/common/hasPermi';
import NewModal from '../../../componentJsx/common/NewModal';
import '../../../componentCss/component.css';
//import '../index.css';

export default class SetExaminee extends Component {
  constructor(props) {
    super(props);
    this.state = {
      examData: {},
      searchTableData: [],
      searchTableCols: [
        {
          title: '工号',
          dataIndex: 'empNo',
          key: 'empNo',
          width: 120,
          fixed: 'left',
          ellipsis: true,
        },
        {
          title: '姓名',
          dataIndex: 'empName',
          key: 'empName',
          width: 120,
          ellipsis: true,
          fixed: 'left',
        },
        {
          title: '地域',
          dataIndex: 'regionName',
          key: 'regionName',
          ellipsis: true,
          width: 100,
        },
        {
          title: '部门BD',
          dataIndex: 'orgBdName',
          key: 'orgBdName',
          ellipsis: true,
          width: 240,
        },
        {
          title: '部门BU',
          dataIndex: 'orgBuName',
          key: 'orgBuName',
          ellipsis: true,
          width: 240,
        },
        {
          title: '部门CU',
          dataIndex: 'orgCuName',
          key: 'orgCuName',
          ellipsis: true,
          width: 240,
        },
        {
          title: '操作',
          dataIndex: '操作',
          key: '操作',
          width: 60,
          fixed: 'right',
          align: 'center',
          render: (t, r) => {
            return (
              <HasPermi
                bottonData={{
                  type: 'link',
                  size: 'small',
                  interceptor:
                    'tmfsExamPlatform:practiceManagement:setExaminee',
                  clickFn: () => this.addEmp(r.empNo),
                  icon: <PlusOutlined />,
                  disabled: this.state.addLoading1,
                }}
              />
            );
          },
        },
      ],
      searchTableLoading: false,
      searchRows: [],
      searchRowKeys: [],
      searchTotal: 0,
      searchPageSize: 10,
      searchPage: 1,
      addTableData: [],
      addTableCols: [
        {
          title: '工号',
          dataIndex: 'empNo',
          key: 'empNo',
          width: 120,
          fixed: 'left',
          ellipsis: true,
        },
        {
          title: '姓名',
          dataIndex: 'empName',
          key: 'empName',
          width: 120,
          ellipsis: true,
          fixed: 'left',
        },
        {
          title: '地域',
          dataIndex: 'regionName',
          key: 'regionName',
          ellipsis: true,
          width: 100,
        },
        {
          title: '部门BD',
          dataIndex: 'orgBdName',
          key: 'orgBdName',
          ellipsis: true,
          width: 240,
        },
        {
          title: '部门BU',
          dataIndex: 'orgBuName',
          key: 'orgBuName',
          ellipsis: true,
          width: 240,
        },
        {
          title: '部门CU',
          dataIndex: 'orgCuName',
          key: 'orgCuName',
          ellipsis: true,
          width: 240,
        },
        {
          title: '操作',
          dataIndex: '操作',
          key: '操作',
          width: 60,
          fixed: 'right',
          align: 'center',
          render: (t, r) => {
            return (
              <HasPermi
                bottonData={{
                  type: 'link',
                  size: 'small',
                  interceptor:
                    'tmfsExamPlatform:practiceManagement:setExaminee',
                  clickFn: () =>
                    this.setState({
                      deleteModalVisible: true,
                      addRows: [r],
                      addRowKeys: [r.empNo],
                    }),
                  icon: <DeleteOutlined style={{ color: '#f00' }} />,
                  disabled: this.state.delLoading1,
                }}
              />
            );
          },
        },
      ],
      addTableLoading: false,
      addRows: [],
      addRowKeys: [],
      addTotal: 0,
      addPageSize: 10,
      addPage: 1,
      searchData: {},
      searchForm: [
        {
          type: 'input',
          name: '工号/姓名',
          code: 'str',
          placeholder: '工号/姓名',
          maxLength: 20,
        },
        {
          type: 'select',
          name: '地域',
          code: 'regionNo',
          options: getDictionaryLabel('addressConfig'),
        },
        {
          type: 'cascader',
          name: '部门',
          code: 'dept',
          options: JSON.parse(
            localStorage.getItem('deptList')
              ? localStorage.getItem('deptList')
              : '[]'
          ),
        },
      ],
      uploadModalVisible: false,
      deleteModalVisible: false,
      addLoading: false,
      delLoading: false,
      addLoading1: false,
      delLoading1: false,
    };
  }
  showUploadModal = () => {
    this.setState({ uploadModalVisible: true });
  };
  hiddenModal = () => {
    this.setState({
      uploadModalVisible: false,
      deleteModalVisible: false,
      // addRows: [],
      // addRowKeys: [],
      // searchRows: [],
      // searchRowKeys: [],
    });
  };
  downloadTemplate = () => {
    exportRisk(
      `/tmfsExamPlatform/examActivityManager/downloadTemplate`,
      '参考员工导入模板.xlsx'
    );
  };
  execSearch = (data) => {
    this.setState({ searchData: data, searchPage: 1 }, () => {
      this.getSearchData();
    });
  };
  execSearch1 = (data) => {
    this.setState({ searchData1: data, addPage: 1 }, () => {
      this.getAddData();
    });
  };
  getSearchData = () => {
    this.setState({ searchTableLoading: true });
    let searchData = this.state.searchData;
    let data = {};
    for (const key in searchData) {
      if (searchData[key] || searchData[key] === 0) {
        if (key == 'str') {
          data.empNoOrName = searchData.str;
        } else if (key === 'dept') {
          const orgType = confirmDeptByCode(
            searchData[key][searchData[key].length - 1]
          );
          if (orgType && orgType.type == 'cu') {
            data.orgCuNo = orgType.value;
          } else if (orgType && orgType.type == 'bu') {
            data.orgBuNo = orgType.value;
          } else if (orgType && orgType.type == 'bd') {
            data.orgBdNo = orgType.value;
          }
        } else {
          data[key] = searchData[key];
        }
      }
    }
    data.currentPage = this.state.searchPage;
    data.pageSize = this.state.searchPageSize;
    data.examId = this.state.examData.id;
    getCandidate(data)
      .then((res) => {
        if (res.data.code == 200) {
          this.setState({
            searchTableData: res.data.data.list,
            searchTotal: res.data.data.total,
            searchTableLoading: false,
            searchRowKeys: [],
            searchRows: [],
          });
        } else {
          message.error(res.data.message || '查询失败');
          this.setState({ searchTableLoading: false });
        }
      })
      .catch((err) => {
        message.error('查询失败');
        this.setState({ searchTableLoading: false });
      });
  };
  getAddData = () => {
    this.setState({ addTableLoading: true });
    let searchData = this.state.searchData1;
    let data = {};
    for (const key in searchData) {
      if (searchData[key] || searchData[key] === 0) {
        if (key == 'str') {
          data.empNoOrName = searchData.str;
        } else if (key === 'dept') {
          const orgType = confirmDeptByCode(
            searchData[key][searchData[key].length - 1]
          );
          if (orgType && orgType.type == 'cu') {
            data.orgCuNo = orgType.value;
          } else if (orgType && orgType.type == 'bu') {
            data.orgBuNo = orgType.value;
          } else if (orgType && orgType.type == 'bd') {
            data.orgBdNo = orgType.value;
          }
        } else {
          data[key] = searchData[key];
        }
      }
    }
    data.currentPage = this.state.addPage;
    data.pageSize = this.state.addPageSize;
    data.examId = this.state.examData.id;
    getEmpInExam(data)
      .then((res) => {
        if (res.data.code == 200) {
          this.setState({
            addTableData: res.data.data.list,
            addTotal: res.data.data.total,
            addTableLoading: false,
            addRowKeys: [],
            addRows: [],
          });
        } else {
          this.setState({ addTableLoading: false });
          message.error(res.data.message || '查询失败');
        }
      })
      .catch((err) => {
        this.setState({ addTableLoading: false });
        message.error('查询失败');
      });
  };
  addEmp = (empNo) => {
    let empList = [];
    if (empNo != -1) {
      this.setState({ addLoading1: true });
      empList = [empNo];
    } else {
      this.setState({ addLoading: true });
      empList = [...this.state.searchRowKeys];
    }
    let data = [];
    empList.forEach((item) => {
      data.push({ testexamId: this.state.examData.id, empNo: item });
    });
    addEmpToExam(data)
      .then((res) => {
        if (res.data.code == 200) {
          message.success('添加成功');
          this.setState({
            Rows: [],
            searchRowKeys: [],
            searchRows: [],
            searchPage: 1,
            addPage: 1,
            addLoading: false,
            addLoading1: false,
          });
          this.getAddData();
          this.getSearchData();
        } else {
          this.setState({
            addLoading: false,
            addLoading1: false,
          });
          message.error(res.data.message || '添加失败');
        }
      })
      .catch((err) => {
        message.error('添加失败');
        this.setState({
          addLoading: false,
          addLoading1: false,
        });
      });
  };
  delEmp = () => {
    this.setState({ confirmLoading: true });
    let data = {};
    let empNoList = this.state.addRowKeys;
    data = { examId: this.state.examData.id, empNoList };
    delEmpInExam(data)
      .then((res) => {
        if (res.data.code == 200) {
          message.success('删除成功');
          this.setState({
            Rows: [],
            searchRowKeys: [],
            searchRows: [],
            searchPage: 1,
            addPage: 1,
            deleteModalVisible: false,
            confirmLoading: false,
          });
          this.getAddData();
          this.getSearchData();
        } else {
          this.setState({
            deleteModalVisible: false,
            confirmLoading: false,
          });
          message.error(res.data.message || '删除失败');
        }
      })
      .catch((err) => {
        message.error('删除失败');
        this.setState({
          deleteModalVisible: false,
          confirmLoading: false,
        });
      });
  };
  onSearchSelectChange = (searchRowKeys, searchRows) => {
    this.setState({ searchRowKeys, searchRows });
  };
  onAddSelectChange = (addRowKeys, addRows) => {
    this.setState({ addRowKeys, addRows });
  };
  searchChangePage = (searchPage, searchPageSize) => {
    this.setState({ searchPage, searchPageSize }, () => {
      this.getSearchData();
    });
  };
  addChangePage = (addPage, addPageSize) => {
    this.setState({ addPage, addPageSize }, () => {
      this.getAddData();
    });
  };
  componentWillMount() {
    if (sessionStorage.getItem('examData')) {
      let examData = JSON.parse(sessionStorage.getItem('examData'));
      this.setState({ examData });
    } else {
      getUrl('/TmfsExam/ExamManagement');
    }
  }
  componentDidMount() {
    this.getSearchData();
    this.getAddData();
  }
  //组件销毁时取消setState
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    const searchRowSelection = {
      selectedRowKeys: this.state.searchRowKeys,
      onChange: this.onSearchSelectChange,
    };
    const addRowSelection = {
      selectedRowKeys: this.state.addRowKeys,
      onChange: this.onAddSelectChange,
    };
    const authToken = window.localStorage.getItem('authToken');
    const token = window.localStorage.getItem('refreshToken');
    let url = getAjaxurl() + `/tmfsExamPlatform/examActivityManager/import`;
    if (devProTest() === 'develop') {
      url =
        window.location.origin + `/tmfsExamPlatform/examActivityManager/import`;
    }
    // ?examId=${this.state.examData.id}
    const _this = this;
    const importProps = {
      action: url,
      name: 'file',
      accept: '.xlsx',
      headers: {
        refreshToken: token,
        authToken: authToken,
      },
      data: { examId: this.state.examData.id },
      onChange(info, event) {
        const { status } = info.file;
        if (status !== 'uploading') {
        }
        if (status === 'done') {
          if (info.file.response.code) {
            if (info.file.response.code == 200) {
              message.success(`请在下载的Excel表格中查看导入结果`, 3);
              downloadExcel(info.file.response.data);
              _this.setState({
                Rows: [],
                searchRowKeys: [],
                searchRows: [],
                searchPage: 1,
                addPage: 1,
              });
              _this.getAddData();
              _this.getSearchData();
            } else if (info.file.response.code == 500) {
              message.error(info.file.response.message || `文件上传失败`, 3);
            } else {
              message.error(`文件上传失败`, 3);
            }
          }
        } else if (status === 'error') {
          message.error(`文件上传失败`);
        }
      },
    };
    const downloadExcel = (data) => {
      let option = {};
      if (data) {
        let _data = [
          {
            empNo: '工号',
            empName: '姓名',
            importError: '结果',
            importMessage: '原因',
          },
          ...data,
        ];
        // 文件名
        option.fileName =
          '参考员工导入详情' + moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        option.datas = [
          {
            sheetData: _data,
            sheetName: 'sheet',
          },
        ];
      }
      // 创建一个ExportJsonExcel实例
      const exportExcel = new ExportJsonExcel(option);
      // 将数据保存到Excel并且导出
      exportExcel.saveExcel();
    };
    return (
      <div className='examWrap'>
        <div className='examInfo'>
          <Space size='large'>
            <span>练习名称：{this.state.examData.name}</span>
            <span>
              练习语言：
              {getDictionaryLabel('language', this.state.examData.language)}
            </span>
            <span>
              练习级别：
              {getDictionaryLabel('examLevel', this.state.examData.level)}
            </span>
          </Space>
        </div>
        {/* <Row gutter={[24, 24]}> */}
        {/* <Col sm={24} xl={12}> */}
        <div className='examTitle'>设置参考员工</div>
        <div>
          <div>
            <AdvancedSearchForm
              execSearch={this.execSearch}
              formData={this.state.searchForm}
              // type='oneItem'
            />
          </div>
          <div>
            <Row>
              <Col span={12}>
                {/* <Button
                  type='primary'
                  onClick={this.addEmp}
                  disabled={this.state.searchRowKeys.length ? false : true}
                >
                  添加
                </Button> */}
                <HasPermi
                  bottonData={{
                    type: 'primary',
                    interceptor:
                      'tmfsExamPlatform:practiceManagement:setExaminee',
                    clickFn: () => {
                      this.addEmp(-1);
                    },
                    text: '添加',
                    disabled: this.state.searchRowKeys.length ? false : true,
                    loading: this.state.addLoading,
                  }}
                />
              </Col>
            </Row>

            <Table
              rowKey='empNo'
              loading={this.state.searchTableLoading}
              scroll={{ x: '100' }}
              rowSelection={{ type: 'checkbox', ...searchRowSelection }}
              columns={this.state.searchTableCols}
              dataSource={this.state.searchTableData}
              pagination={{
                total: this.state.searchTotal,
                pageSize: this.state.searchPageSize,
                current: this.state.searchPage,
                showSizeChanger: true,
                onChange: this.searchChangePage,
                // onShowSizeChange: this.changePageSize,
                showTotal: (total) => '共 ' + total + ' 条',
              }}
              size='small'
              bordered
            />
          </div>
        </div>
        {/* </Col> */}
        {/* <Col sm={24} xl={12}> */}
        <div className='examTitle'>已添加员工</div>
        <div
        // style={{ marginTop: 56 }}
        >
          <div>
          <AdvancedSearchForm
              execSearch={this.execSearch1}
              formData={this.state.searchForm}
              // type='oneItem'
            />
          </div>
          <div>
            <Row>
              <Col span={12}>
                <Space>
                  <HasPermi
                    bottonData={{
                      type: 'danger',
                      interceptor:
                        'tmfsExamPlatform:practiceManagement:setExaminee',
                      clickFn: () =>
                        this.setState({ deleteModalVisible: true }),
                      text: '删除',
                      disabled: !this.state.addRowKeys.length,
                      loading: this.state.delLoading,
                    }}
                  />
                  <HasPermi
                    bottonData={{
                      interceptor:
                        'tmfsExamPlatform:practiceManagement:setExaminee',
                      clickFn: this.getAddData,
                      text: '刷新',
                    }}
                  />
                </Space>
              </Col>
              <Col style={{ textAlign: 'right' }} span={12}>
                <Space>
                  <HasPermi
                    bottonData={{
                      type: 'link',
                      interceptor:
                        'tmfsExamPlatform:practiceManagement:setExaminee',
                      clickFn: this.downloadTemplate,
                      text: '下载模板',
                    }}
                  />
                  <HasPermi
                    bottonData={{
                      interceptor:
                        'tmfsExamPlatform:practiceManagement:setExaminee',
                      clickFn: this.showUploadModal,
                      text: '导入',
                    }}
                  />
                </Space>
              </Col>
            </Row>

            <Table
              rowKey='empNo'
              loading={this.state.addTableLoading}
              scroll={{ x: '100' }}
              rowSelection={{ type: 'checkbox', ...addRowSelection }}
              columns={this.state.addTableCols}
              dataSource={this.state.addTableData}
              pagination={{
                total: this.state.addTotal,
                pageSize: this.state.addPageSize,
                current: this.state.addPage,
                showSizeChanger: true,
                onChange: this.addChangePage,
                // onShowSizeChange: this.changePageSize,
                showTotal: (total) => '共 ' + total + ' 条',
              }}
              size='small'
              bordered
            />
          </div>
        </div>
        {/* </Col> */}
        {/* </Row> */}

        <div>
          <Space>
            <Button
              onClick={() => {
                getUrl('/TmfsExam/PracticeManagement');
              }}
            >
              返回
            </Button>
            {/* <Button
              type='primary'
              onClick={this.editExam}
              loading={this.state.confirmLoading}
            >
              确认
            </Button> */}
            {/* <Button
              onClick={() => {
                getUrl('/TmfsExam/ExamManagement');
              }}
              type='link'
            >
              取消
            </Button> */}
          </Space>
        </div>
        <NewModal
          modalOptions={{
            width: '500px',
            title: '导入参考员工',
            visible: this.state.uploadModalVisible,
            onCancel: this.hiddenModal,
            destroyOnClose: true,
          }}
          buttonOptions={{
            position: 'center',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '关闭',
              },
            ],
          }}
        >
          <Upload.Dragger {...importProps}>
            <p className='ant-upload-drag-icon'>
              <InboxOutlined />
            </p>
            <p className='ant-upload-text'>
              单击选择或拖动文件到该区域进行上传
            </p>
            <p className='ant-upload-hint'>
              单个文件最大限制
              <span style={{ color: 'red' }}>5000</span>行，仅支持
              <span style={{ color: 'red' }}>.xlsx</span>
              格式
            </p>
          </Upload.Dragger>
        </NewModal>
        {/* 删除 */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: '删除提示',
            visible: this.state.deleteModalVisible,
            onCancel: this.hiddenModal,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
              {
                key: 0,
                onClick: this.delEmp,
                text: '确认删除',
                type: 'danger',
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <DeleteFilled
            style={{
              fontSize: '28px',
              color: '#e00',
              float: 'left',
              backgroundColor: '#f002',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              height: 44,
              lineHeight: '44px',
            }}
          >
            删除后员工考试记录会一并删除，确定删除？
          </div>
        </NewModal>
      </div>
    );
  }
}
